// 路由鉴权，项目中路由能不能被权限的设置
import router from '@/router'
import setting from '@/setting'
// 引入进度条
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
// 获取用户相关的小仓库内部token数据，去判断用户是否登录
import useUserStore from '@/store/modules/user'
// 引入大仓库
import pinia from '@/store'

nprogress.configure({ showSpinner: false })

const userStore = useUserStore(pinia)

// 全局前置守卫
router.beforeEach(async (to: any, from: any, next: any) => {
  document.title = `${setting.title}-${to.meta.title}`
  // to:访问的路由 from:从哪个路由过来的 next:路由放行的函数
  nprogress.start()
  // 获取token
  const token: string = userStore.token
  // 获取用户名称
  const username = userStore.username
  if (token) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      // 登录成功访问其余的路由
      if (username) {
        next()
      } else {
        try {
          // 获取用户信息
          await userStore.userInfo()
          next({...to})
        } catch (error) {
          // token过期
          await userStore.userLoginOut()
          next({ path: '/login', query: { redirect: to.path } })
        }
      }
    }
  } else {
    if (to.path === '/login') {
      next()
    } else {
      next({ path: '/login', query: { redirect: to.path } })
    }
  }
})
// 全局后置守卫
router.afterEach((to: any, from: any) => {
  nprogress.done()
})
